import React, { useEffect, useMemo, useState } from 'react';
import { useLocation, history } from 'umi';
import { Tabs } from 'antd';
import styles from './styles.less';
import _ from 'lodash';
import { NavTabAPI } from './type';
import NavTabExtraContent from './components/NavTabExtraContent';
import ErrorBoundary from '@/components/ErrorBoundary';
// import HomePage from '@/pages/HomePage';
import { getPageRouterOA, getSystemType, useSystemHomeRouterText } from '@/utils';
import ContractHomePage from '@/pages/ContractController/ContractHomePage/mview/ContractHomePage';
// import HomePage from '@/pages/HomePage';
import PurchaseGateway from '@/pages/PurchaseManage/PurchaseGateway/mview/ManageView';
import Fixedassetportal from '@/pages/AssetManage/Fixedassetportal/mview/ManageView';

export const NavTabs: React.FC<NavTabAPI.INavTabType> = ({ navTab, curRes, dispatch, children, baseLogin }) => {
  let { allTabs } = navTab;

  const location = useLocation();

  const [taskFlag, setTaskFlag] = useState<boolean>(true); //开关
  useEffect(() => {
    if (location && location?.pathname == '/welcome') {
      if (curRes?.['/expertInfoController/manage'] && taskFlag && getSystemType() == '4') {
        setTaskFlag(false);
        history?.push({
          pathname: '/expertInfoController/manage',
        });
      }
    } else {
      setTaskFlag(false);
    }
  }, [curRes, location]);

  const homePageRouterText = useMemo(() => {
    return useSystemHomeRouterText(curRes);
  }, [curRes]);

  /**
   * 保存当前选中的tab页面key
   */
  const [pageTabpaneKey, setPageTabpaneKey] = useState<string>('');

  // 处理删除上一个路由
  const handleDelRouter = (tabList: any[]) => {
    let prevRouter: any[] = [];
    tabList?.forEach((item: any) => {
      if (item?.locationProps?.state?.delRouterName) {
        prevRouter?.push(item?.locationProps?.state?.delRouterName);
      }
    });
    return prevRouter;
  };

  let TabList = React.useMemo(() => {
    let tabList: any[] = [];
    let newTabListPage: any[] = handleDelRouter(allTabs);
    allTabs?.forEach((item) => {
      if (!newTabListPage.includes(item?.pathname)) {
        tabList?.push({ ...item });
      }
    });
    return tabList;
  }, [allTabs]);

  /* tabs编辑方法 */
  const onTabsEdit = (currentID: any) => {
    let allTabs: any[] = TabList?.filter((item: any) => {
      return item?.pathname != currentID;
    });
    // let allTabs = _.cloneDeep(TabList);
    if (TabList && TabList?.length > 0) {
      // TabList?.forEach((item: any, index) => {
      //   if (item?.pathname != currentID) {
      //     // allTabs?.splice(index, 1);
      //     allTabs?.push(item)
      //   }
      // });

      dispatch({
        type: 'navTab/updateWindow',
        payload: allTabs,
      });
      if (allTabs?.length > 0) {
        // history.push(allTabs?.[allTabs?.length - 1]?.pathname);
        window.location.hash = allTabs?.[allTabs?.length - 1]?.pathname;
        // setPageTabpaneKey(allTabs?.[allTabs?.length - 1]?.pathname)
      } else {
        // history.push('/welcome');
        // window.location.hash = '/welcome';
        window.location.hash = homePageRouterText;
      }
    }
  };
  const [flag, setFlag] = useState(false);

  useEffect(() => {
    if ((location.state as any)?.delRouterNameSource) {
      setFlag(false);
      if (!flag) {
        setFlag(true);
        onTabsEdit((location.state as any)?.delRouterNameSource);
      }
    }

    if (TabList?.length == 0) {
      // setPageTabpaneKey('/welcome');
      setPageTabpaneKey(location?.pathname || homePageRouterText);
    } else if (location?.pathname) {
      setPageTabpaneKey(location?.pathname);
    }
  }, [TabList, location?.pathname]);

  /**
   * 菜单tab页面改变
   * @param currentID
   */
  const onTabsChange = (currentID: any) => {
    if (currentID) {
      window.location.hash = currentID;

      // let currentObj: any = TabList?.find((item: any) => {
      //   return item?.pathname == currentID;
      // });

      // if (currentObj?.locationProps?.pathname) {
      //    history.push({
      //      ...currentObj?.locationProps,
      //      pathname: currentObj?.locationProps?.pathname,
      //      query: currentObj?.locationProps?.query,
      //      state: currentObj?.locationProps?.state,
      //    });
      //   window.location.hash = currentID
      //    setPageTabpaneKey(currentID)
      // } else {
      //   history.push(currentID);
      // }
    }
  };

  /**
   * 4.23 版本 antd tab组件
   */
  const tabPanePages: any = useMemo(() => {
    let tabList: any = [
      // {
      //   label: '主页',
      //   key: '/welcome',
      //   closable: false,
      //   children: (
      //     <ErrorBoundary>
      //       <HomePage curRes={curRes} baseLoginProps={baseLogin} homeDispatch={dispatch} />
      //     </ErrorBoundary>
      //   ),
      // },
    ];

    if (curRes?.['/purchaseGateway/manage'] && baseLogin?.userInfo?.id && getSystemType() == '1') {
      tabList?.push({
        label: '采购门户',
        key: '/purchaseGateway/manage',
        closable: false,
        children: (
          <ErrorBoundary>
            {/* <HomePage curRes={curRes} baseLoginProps={baseLogin} homeDispatch={dispatch} /> */}
            {/* <ContractHomePage /> */}
            <PurchaseGateway />
          </ErrorBoundary>
        ),
      });
    }

    if (curRes?.['/contractController/homePage'] && baseLogin?.userInfo?.id && getSystemType() == '2') {
      tabList?.push({
        label: '合同门户',
        key: '/contractController/homePage',
        closable: false,
        children: (
          <ErrorBoundary>
            {/* <HomePage curRes={curRes} baseLoginProps={baseLogin} homeDispatch={dispatch} /> */}
            <ContractHomePage />
          </ErrorBoundary>
        ),
      });
    }

    if (curRes?.['/fixedassetportal/manage'] && baseLogin?.userInfo?.id && getSystemType() == '3') {
      tabList?.push({
        label: '资产门户',
        key: '/fixedassetportal/manage',
        closable: false,
        children: (
          <ErrorBoundary>
            <Fixedassetportal />
          </ErrorBoundary>
        ),
      });
    }

    if (TabList && TabList?.length > 0) {
      TabList?.forEach((item: any) => {
        let tabItem: Record<string, any> = {
          label: item?.name,
          key: item?.pathname,
          children: (
            <ErrorBoundary>
              {
                // children ? (
                item?.domChildPage ? (
                  // item?.pathname === location.pathname &&
                  // React.cloneElement(children as any, {
                  React.cloneElement(item?.domChildPage as any, {
                    locationProps: item?.locationProps ?? '',
                  })
                ) : (
                  <></>
                )
              }
            </ErrorBoundary>
          ),
        };
        tabList?.push(tabItem);
      });
    }

    return tabList;
  }, [allTabs, baseLogin?.openWelcomeLayout, baseLogin?.userInfo, curRes]);

  /** 处理tabs头部dom,区分于OA页面 */
  const navTabsHeardCss = (): React.CSSProperties => {
    let cssConfig: React.CSSProperties = {
      background: '#fff',
      borderBottom: '1px solid #eee',
      marginBottom: 0,
    };
    if (getPageRouterOA()) {
      cssConfig['display'] = 'none';
    }
    return cssConfig;
  };

  return (
    <div id={'NavTabs'} className={styles['nav-tabs']}>
      <Tabs
        // defaultActiveKey="/welcome"
        defaultActiveKey={homePageRouterText || location?.pathname}
        type="editable-card"
        hideAdd={true}
        tabBarStyle={navTabsHeardCss()}
        style={{ height: '100%' }}
        onEdit={onTabsEdit}
        // activeKey={location?.pathname}
        activeKey={pageTabpaneKey}
        onChange={onTabsChange}
        tabBarExtraContent={<NavTabExtraContent dispatch={dispatch} activeKey={pageTabpaneKey} tabsList={TabList} homePageRouterText={homePageRouterText} />}
        items={tabPanePages}
      />
    </div>
  );
};

// export default connect(({ navTab, baseLogin }: any) => ({
//   navTab,
//   curRes: baseLogin?.permissions,
//   baseLogin: baseLogin,
// }))(NavTabs);
